﻿using System;
using System.Windows.Forms;
using Settings = OMC.Properties.Settings;
using Manager = OMC.DataManagement.Manager;
using StringResources = OMC.Properties.StringResources;
using System.Resources;
using System.Threading;
using System.ComponentModel;
using System.Diagnostics;

namespace OMC.UserInterface
{
    /// <summary>
    /// MyForm is a form to display options. the options form could be use to
    /// customize the Add-In "Outlook Mail Classifier".
    /// </summary>
    partial class MyForm : Form
    {
        Manager manager;
        bool settingsChanged;
        string TheTextOfSaveFileDialogFilter;
        string TheTextOfSaveFileDialogTitle;

        /// <summary>
        /// The constructor to create a new object of MyForm, it needs a Manager Object
        /// </summary>
        public MyForm(Manager manager)
        {
            this.manager = manager;
            this.settingsChanged = false;
            InitializeComponent();
            InitializeRessources();
            resultOfTestCl.Visible = false;
            comboBoxClassifier.DropDownStyle = ComboBoxStyle.DropDownList;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.progressBar1.Visible = false;
            this.progressBar1.Style = ProgressBarStyle.Marquee;
            this.buttonMore.Visible = false;
        }

        /// <summary>
        /// The Method get the settings and commit them to the form settings.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">The EventArgs object</param>
        private void MyForm_Load(object sender, EventArgs e)
        {
            checkBoxUseStopwords.Checked = Settings.Default.luceneAnalyzer;
            comboBoxClassifier.SelectedIndex = Settings.Default.classifierIndex;
            trackBarCountItemContextMenu.Value = Settings.Default.trackBarIndex;
            labelTrackBarN.Text = Convert.ToString(trackBarCountItemContextMenu.Value);
        }

        /// <summary>
        /// The Method set the state of the checkBox to the settings.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">The EventArgs object</param>
        private void checkBoxUseStopWords_CheckedChanged(object sender, EventArgs e)
        {
            settingsChanged = true;
            Settings.Default.luceneAnalyzer = checkBoxUseStopwords.Checked;
        }

        /// <summary>
        /// The Method set the choosen classifier to the settings.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">The EventArgs object</param>
        private void comboBoxClassifier_SelectedIndexChanged(object sender, EventArgs e)
        {
            settingsChanged = true;
            Settings.Default.classifierIndex = comboBoxClassifier.SelectedIndex;
        }

        /// <summary>
        /// The Method handle the click of the button.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">The EventArgs object</param>
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (settingsChanged)
            {
                //save the settings 
                Settings.Default.Save();
                if (manager.IsDataSetLoaded())
                {
                    manager.refresh();
                }
                settingsChanged = false;
            }
            this.Close();
        }

        private void buttonShowLogFile_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.EnableRaisingEvents = false;
                process.StartInfo.FileName = @"C:\Windows\Temp\rolling.log";
                process.Start();
            }
            catch (Exception ex)
            {
                //user message
                MessageBox.Show("Not possible to open Log file");
                //log file entry
                String message = "It isn't possible to open the Log file";
                Utils.Debug.Log(message, ex, TraceEventType.Error);
            }
        }

        private void buttonTestCl_Click(object sender, EventArgs e)
        {
            resultBox.Text = "";
            resultOfTestCl.Visible = false;
            this.buttonMore.Visible = false;
            buttonTestCl.Enabled = false;
            progressBar1.Visible = true;
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += bgw_DoWork;
            bgw.RunWorkerCompleted += bgw_Completed;
            bgw.RunWorkerAsync();
        }

        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            lock (this)
            {
                if (settingsChanged)
                {
                    //save the settings 
                    Settings.Default.Save();
                    if (manager.IsDataSetLoaded())
                    {
                        manager.refresh();
                    }
                    settingsChanged = false;
                }
                while (!manager.IsDataSetLoaded())
                {
                    Monitor.Wait(this, 1000);
                }
            }
        }

        void bgw_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Invoke(new MethodInvoker(finishAfterTesting));
            ((BackgroundWorker)sender).Dispose();
        }

        private void finishAfterTesting()
        {
            progressBar1.Visible = false;
            resultOfTestCl.Visible = true;
            resultBox.Text = manager.getGoodness() + " %";
            this.buttonMore.Visible = true;
            buttonTestCl.Enabled = true;
        }


        private void trackBarCountItemContextMenu_Scroll(object sender, EventArgs e)
        {
            labelTrackBarN.Text = Convert.ToString(trackBarCountItemContextMenu.Value);
            Settings.Default.trackBarIndex = trackBarCountItemContextMenu.Value;
            Settings.Default.Save();
            manager.SetTrackbarIndex();
        }

        private void buttonMore_Click(object sender, EventArgs e)
        {
            MessageBox.Show(manager.getGoodnessExtra());
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            buttonRefresh.Enabled = false;
            if (manager.IsDataSetLoaded())
            {
                manager.refresh();
            }
            buttonRefresh.Enabled = true;
        }

        private void buttonArffSaver_Click(object sender, EventArgs e)
        {
            buttonArffSaver.Enabled = false;
            // Displays a SaveFileDialog so the user can save the Image
            // assigned to Button2.
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = TheTextOfSaveFileDialogFilter;
                saveFileDialog.Title = TheTextOfSaveFileDialogTitle;
                saveFileDialog.ShowDialog();

                // If the file name is not an empty string open it for saving.
                if (saveFileDialog.FileName != "")
                {
                    String TheFilePath = saveFileDialog.InitialDirectory + saveFileDialog.FileName;
                    switch (saveFileDialog.FilterIndex)
                    {
                        case 1: //default Weka arff file
                            manager.SaveToFile(TheFilePath, false);
                            break;
                        case 2: //filtered Weka arff file
                            manager.SaveToFile(TheFilePath, true);
                            break;
                    }
                }
            }
            buttonArffSaver.Enabled = true;
        }

        private void InitializeRessources()
        {
            ResourceManager rm = StringResources.ResourceManager;

            //SaveDialog Strigs
            TheTextOfSaveFileDialogFilter = rm.GetString("saveFileDialogFilter");
            TheTextOfSaveFileDialogTitle = rm.GetString("saveFileDialogTitle");

            //Set Resources
            groupBoxPreprocess.Text = rm.GetString("groupBoxPreprocess");
            groupBoxClassification.Text = rm.GetString("groupBoxClassification");
            labelOfPreprocessor.Text = rm.GetString("labelOfPreprocessor");
            checkBoxUseStopwords.Text = rm.GetString("checkBoxUseStopwords");
            comboBoxClassifier.Text = rm.GetString("comboBoxClassifier");
            comboBoxClassifier.Items.Add("NaiveBayes Multinomial Updateable");
            comboBoxClassifier.Items.Add("NaiveBayes Multinomial");
            comboBoxClassifier.Items.Add("Complement NaiveBayes");
            comboBoxClassifier.Items.Add("DMNB Text");
            buttonSave.Text = rm.GetString("buttonSave");
            buttonShowLogFile.Text = rm.GetString("buttonLog");
            groupBoxExtension.Text = rm.GetString("groupBoxExtension");
            labelOfContextMenuCount.Text = rm.GetString("labelOfContextMenuCount");
            labelLogFile.Text = rm.GetString("labelLogFile");
            groupBoxDisplay.Text = rm.GetString("groupBoxDisplay");
            groupBoxClTest.Text = rm.GetString("groupBoxClTest");
            buttonMore.Text = rm.GetString("buttonMore");
            buttonTestCl.Text = rm.GetString("buttonTestCl");
            tabClassification.Text = rm.GetString("tabClassification");
            tabDisplay.Text = rm.GetString("tabDisplay");
            tabExtended.Text = rm.GetString("tabExtended");
            resultOfTestCl.Text = rm.GetString("resultOfTest");
            groupBoxDataset.Text = rm.GetString("groupBoxDataset");
            labelRefresh.Text = rm.GetString("labelRefresh");
            buttonRefresh.Text = rm.GetString("buttonRefresh");
            labelSaveToArff.Text = rm.GetString("labelSaveToArff");
            buttonArffSaver.Text = rm.GetString("buttonArffSaver");
            resultBox.Text = "";
            this.Text = rm.GetString("optionsTitle");
        }
    }
}